import 'package:flutter/material.dart';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/exam_model.dart';
import '../models/question_model.dart';
import '../services/exam_service.dart';
import '../services/exam_state_service.dart';
import '../services/exam_session_service.dart';
import '../services/photo_state_service.dart';
import '../utils/responsive_util.dart';
import '../data/user_data.dart';
import 'result_screen.dart';
import 'dart:io';
import '../services/image_service.dart';

// 导入用户数据以获取管理员密码
import '../data/user_data.dart';

class ExamScreen extends StatefulWidget {
  final Exam exam;
  final ExamState? initialState; // 可选的初始状态，用于恢复考试
  final String? avatarPath; // 新增：头像路径
  
  const ExamScreen({
    super.key, 
    required this.exam, 
    this.initialState,
    this.avatarPath,
  });

  @override
  State<ExamScreen> createState() => _ExamScreenState();
}

class _ExamScreenState extends State<ExamScreen> with WidgetsBindingObserver {
  late PageController _pageController;
  int _currentIndex = 0;
  Map<String, dynamic> _answers = {}; // 存储答案，key为题目ID，value为答案
  Set<String> _markedQuestions = {}; // 存储标记的题目ID
  Timer? _timer;
  int _remainingSeconds = 0;
  bool _isSubmitting = false;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  Timer? _autoSaveTimer; // 自动保存计时器
  final ScrollController _scrollController = ScrollController();
  final Map<String, dynamic> _userAnswers = {};
  final Map<String, int> _questionIndexMap = {};
  bool _isExamSubmitted = false;
  bool _showConfirmDialog = false;
  Timer? _examTimer;
  Timer? _saveStateTimer;
  ExamResult? _examResult;
  
  // 新增：用于存储答题照片的字段
  final Map<String, List<String>> _answerImages = {};
  
  // 新增：考试暂停状态
  bool _isPaused = false;
  // 新增：暂停对话框控制器
  late TextEditingController _passwordController;
  // 新增：简答题输入框控制器映射
  final Map<String, TextEditingController> _textControllers = {};

  // 新增：拍照状态标记
  bool _isTakingPhoto = false;

  // 新增：主动离开考试标记
  bool _isLeavingExam = false;

  // 同步删除考试状态的方法
  void _removeExamStateSync(String examId, String userId) {
    try {
      debugPrint('开始同步删除考试状态: $examId, $userId');
      // 直接调用SharedPreferences的同步方法
      final key = 'exam_state_${examId}_$userId';
      SharedPreferences.getInstance().then((prefs) {
        final removed = prefs.remove(key);
        debugPrint('考试状态删除结果: $removed');
      });
    } catch (e) {
      debugPrint('同步删除考试状态失败: $e');
    }
  }

  @override
  void initState() {
    super.initState();

    // 添加应用生命周期监听器
    WidgetsBinding.instance.addObserver(this);

    // 启动考试会话，防止自动退出
    final currentUser = UserData.currentUser;
    if (currentUser != null) {
      final examId = widget.initialState?.examId ?? widget.exam.id;
      ExamSessionService().startExamSession(examId, currentUser.id);
      debugPrint('🎯 已启动考试会话，禁用自动退出');
    }

    // 初始化密码控制器
    _passwordController = TextEditingController();

    // 初始化页面控制器
    _pageController = PageController();

    // 初始化简答题输入框控制器
    _initializeTextControllers();

    // 如果提供了初始状态，恢复考试状态
    if (widget.initialState != null) {
      _restoreState(widget.initialState!);
    } else {
      // 否则开始新考试
      _startNewExam();
    }

    // 设置自动保存定时器（每30秒保存一次，从60秒改为30秒）
    _autoSaveTimer = Timer.periodic(const Duration(seconds: 30), (_) {
      _autoSaveExamState();
    });
  }

  // 恢复考试状态
  void _restoreState(ExamState state) {
    debugPrint('=== 恢复考试状态 ===');
    debugPrint('原始答案数量: ${state.answers.length}');
    debugPrint('剩余时间: ${state.remainingSeconds} 秒');

    // 创建一个新的答案映射，以确保我们不会修改原始状态
    Map<String, dynamic> restoredAnswers = Map<String, dynamic>.from(state.answers);

    // 移除可能存在的系统标记，避免数据污染
    restoredAnswers.remove('_active_session');
    restoredAnswers.remove('_answerImages');

    debugPrint('清理后答案数量: ${restoredAnswers.length}');

    setState(() {
      _answers = restoredAnswers;
      _remainingSeconds = state.remainingSeconds;
      _isPaused = false; // 确保从初始状态恢复时不是暂停状态

      // 恢复答题照片信息（如果有）
      if (state.answers.containsKey('_answerImages')) {
        final Map<String, dynamic> savedImages = state.answers['_answerImages'];
        savedImages.forEach((questionId, paths) {
          if (paths is List) {
            _answerImages[questionId] = List<String>.from(paths);
          }
        });
        debugPrint('恢复了 ${_answerImages.length} 个题目的答题照片');
      }
    });

    // 更新文本控制器的内容
    _updateTextControllers();

    debugPrint('✅ 考试状态恢复完成，不创建新状态');
    _startTimer();
  }

  // 开始新考试
  void _startNewExam() async {
    debugPrint('=== 开始新考试 ===');
    debugPrint('考试ID: ${widget.exam.id}');
    debugPrint('考试时长: ${widget.exam.duration} 分钟');

    // 创建考试状态
    final ExamState? state = await ExamStateService.startExam(widget.exam.id, widget.exam.duration);

    if (state != null) {
      debugPrint('✅ 考试状态创建成功');
      setState(() {
        _answers = <String, dynamic>{}; // 空的答案映射
        _remainingSeconds = widget.exam.duration * 60; // 转换为秒
      });

      debugPrint('新考试初始化完成，答案数量: ${_answers.length}');
    } else {
      debugPrint('❌ 考试状态创建失败，使用默认设置');
      setState(() {
        _answers = <String, dynamic>{}; // 空的答案映射
        _remainingSeconds = widget.exam.duration * 60; // 转换为秒
      });
    }

    _startTimer();
  }

  // 自动保存考试状态
  void _autoSaveExamState() {
    // 如果考试已经提交，不再保存状态
    if (_isSubmitting) {
      debugPrint('考试已提交，跳过自动保存');
      return;
    }

    // 使用正确的考试ID进行保存
    // 如果是恢复的考试，使用原始状态中的考试ID
    // 如果是新开始的考试，使用当前考试的ID
    final examIdForSave = widget.initialState?.examId ?? widget.exam.id;

    ExamStateService.autoSaveExamState(
      examIdForSave,
      _answers,
      _remainingSeconds,
    ).then((success) {
      // 再次检查是否已提交，防止异步操作完成时状态已改变
      if (_isSubmitting) {
        debugPrint('考试已提交，忽略自动保存结果');
        return;
      }

      if (success) {
        debugPrint('考试状态自动保存成功 (考试ID: $examIdForSave)');
      } else {
        debugPrint('考试状态自动保存失败 (考试ID: $examIdForSave)');
      }
    });
  }

  @override
  void dispose() {
    // 结束考试会话，恢复自动退出功能
    ExamSessionService().endExamSession();
    debugPrint('🏁 已结束考试会话，恢复自动退出功能');

    // 移除应用生命周期监听器
    WidgetsBinding.instance.removeObserver(this);

    _pageController.dispose();
    _timer?.cancel();
    _autoSaveTimer?.cancel();
    _passwordController.dispose(); // 新增：释放密码控制器

    // 释放简答题输入框控制器
    for (var controller in _textControllers.values) {
      controller.dispose();
    }
    _textControllers.clear();
    
    // 退出前处理考试状态
    if (_isSubmitting) {
      // 考试已提交，不需要任何状态处理
      debugPrint('考试已提交，跳过状态处理');
    } else if (_isLeavingExam) {
      // 用户主动离开考试，删除考试状态，避免显示未完成考试对话框
      debugPrint('用户主动离开考试，删除考试状态');
      final currentUser = UserData.currentUser;
      if (currentUser != null) {
        // 确定要删除的考试状态ID
        final examIdForStateRemoval = widget.initialState?.examId ?? widget.exam.id;
        // 同步删除，确保在dispose完成前删除状态
        _removeExamStateSync(examIdForStateRemoval, currentUser.id);
      }
    } else {
      // 异常退出（如应用被杀死），保存状态以便恢复
      debugPrint('考试页面被销毁，保存状态但保留活动会话标记');

      // 使用正确的考试ID进行保存
      final examIdForSave = widget.initialState?.examId ?? widget.exam.id;

      // 保存当前状态，保留活动会话标记
      ExamStateService.autoSaveExamState(
        examIdForSave,
        _answers,
        _remainingSeconds
      );
    }
    
    super.dispose();
  }

  // 处理应用生命周期状态变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (state == AppLifecycleState.paused) {
      // 应用进入后台，保存考试状态
      debugPrint('考试页面：应用进入后台');
      debugPrint('全局拍照状态: ${PhotoStateService().isTakingPhoto}');

      // 无论是否拍照，都保存考试状态
      debugPrint('应用进入后台，保存考试状态');
      _saveExamState();

    } else if (state == AppLifecycleState.resumed) {
      // 应用恢复前台
      debugPrint('考试页面：应用恢复前台');
      debugPrint('本地拍照状态: $_isTakingPhoto');
      debugPrint('全局拍照状态: ${PhotoStateService().isTakingPhoto}');

      if (_isTakingPhoto || PhotoStateService().isTakingPhoto) {
        // 如果是从拍照返回，更新活动时间戳
        debugPrint('从拍照返回，更新活动时间戳');

        // 活动时间戳现在由ExamState管理，不需要在answers中设置

        // 延迟保存状态，避免立即触发检查
        Future.delayed(Duration(milliseconds: 200), () {
          if (mounted) {
            _saveExamState();
          }
        });
      } else {
        // 如果不是从拍照返回，也更新活动时间戳（表示用户回到了考试）
        debugPrint('从桌面返回考试，更新活动时间戳');
        // 活动时间戳现在由ExamState管理，不需要在answers中设置

        // 延迟保存状态
        Future.delayed(Duration(milliseconds: 200), () {
          if (mounted) {
            _saveExamState();
          }
        });
      }
    }
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        // 仅在考试未暂停时减少剩余时间
        if (!_isPaused && _remainingSeconds > 0) {
          _remainingSeconds--;
        } else if (!_isPaused && _remainingSeconds <= 0) {
          _timer?.cancel();
          _handleTimeUp(); // 时间结束处理，不自动提交
        }
      });
    });
  }

  // 初始化简答题和填空题输入框控制器
  void _initializeTextControllers() {
    for (var question in widget.exam.questions) {
      if (question.type == QuestionType.shortAnswer) {
        // 简答题使用单个控制器
        final controller = TextEditingController();
        final initialText = _answers[question.id] as String? ?? '';
        controller.text = initialText;
        _textControllers[question.id] = controller;
      } else if (question.type == QuestionType.fillBlank) {
        // 填空题需要根据是否为多空来初始化控制器
        final fillBlankQuestion = question as FillBlankQuestion;
        if (fillBlankQuestion.isMultiBlank) {
          // 多空填空题：为每个空创建单独的控制器
          final currentAnswers = _answers[question.id] as List<String>? ??
                                List<String>.filled(fillBlankQuestion.blankCount, '');

          for (int i = 0; i < fillBlankQuestion.blankCount; i++) {
            final controllerId = '${question.id}_$i';
            final controller = TextEditingController();
            controller.text = i < currentAnswers.length ? currentAnswers[i] : '';
            _textControllers[controllerId] = controller;
          }
        } else {
          // 单空填空题：使用单个控制器
          final controller = TextEditingController();
          final initialText = _answers[question.id] as String? ?? '';
          controller.text = initialText;
          _textControllers[question.id] = controller;
        }
      }
    }
  }

  // 更新文本控制器的内容（用于恢复状态时）
  void _updateTextControllers() {
    for (var question in widget.exam.questions) {
      if (question.type == QuestionType.shortAnswer) {
        // 简答题更新单个控制器
        final controller = _textControllers[question.id];
        if (controller != null) {
          final text = _answers[question.id] as String? ?? '';
          if (controller.text != text) {
            controller.text = text;
          }
        }
      } else if (question.type == QuestionType.fillBlank) {
        // 填空题需要根据是否为多空来更新控制器
        final fillBlankQuestion = question as FillBlankQuestion;
        if (fillBlankQuestion.isMultiBlank) {
          // 多空填空题：更新每个空的控制器
          final currentAnswers = _answers[question.id] as List<String>? ??
                                List<String>.filled(fillBlankQuestion.blankCount, '');

          for (int i = 0; i < fillBlankQuestion.blankCount; i++) {
            final controllerId = '${question.id}_$i';
            final controller = _textControllers[controllerId];
            if (controller != null) {
              final text = i < currentAnswers.length ? currentAnswers[i] : '';
              if (controller.text != text) {
                controller.text = text;
              }
            }
          }
        } else {
          // 单空填空题：更新单个控制器
          final controller = _textControllers[question.id];
          if (controller != null) {
            final text = _answers[question.id] as String? ?? '';
            if (controller.text != text) {
              controller.text = text;
            }
          }
        }
      }
    }
  }

  // 处理时间结束，只保存状态不自动提交
  void _handleTimeUp() async {
    // 保存当前状态
    await _saveExamState();

    // 显示时间结束提示，但不自动提交
    if (mounted) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => AlertDialog(
          title: const Row(
            children: [
              Icon(Icons.access_time, color: Colors.orange),
              SizedBox(width: 8),
              Text('考试时间结束'),
            ],
          ),
          content: const Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '考试时间已结束，您的答题进度已自动保存。',
                style: TextStyle(fontSize: 16),
              ),
              SizedBox(height: 12),
              Text(
                '您可以选择：',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              Text('• 立即提交考试'),
              Text('• 退出考试（稍后可以继续）'),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                // 设置主动离开标记
                _isLeavingExam = true;
                Navigator.of(context).pop(); // 关闭对话框
                Navigator.of(context).pop(); // 退出考试页面
              },
              child: const Text('退出考试'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
                _submitExam(); // 手动提交
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red.shade700,
                foregroundColor: Colors.white,
              ),
              child: const Text('提交考试'),
            ),
          ],
        ),
      );
    }
  }

  String _formatTime(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;
    int secs = seconds % 60;

    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }

  void _submitExam() {
    if (_isSubmitting) return; // 防止重复提交
    
    // 重新计算未答题数量，同时考虑照片答案
    int answeredCount = 0;
    for (var question in widget.exam.questions) {
      if (_isQuestionAnswered(question.id)) {
        answeredCount++;
      }
    }
    
    int unansweredCount = widget.exam.questions.length - answeredCount;
    
    // 显示确认对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认提交'),
        content: Text(
          unansweredCount > 0
              ? '您还有 $unansweredCount 道题未作答，确定要提交吗？' 
              : '确定要提交考试吗？'
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(); // 关闭对话框
              _doSubmitExam(); // 执行提交
            },
            child: Text('确认提交'),
          ),
        ],
      ),
    );
  }
  
  // 实际执行提交的方法
  Future<void> _doSubmitExam() async {
    // 立即取消自动保存定时器，防止在提交过程中继续保存状态
    _autoSaveTimer?.cancel();
    debugPrint('已取消自动保存定时器');

    // 立即设置提交标志，防止任何保存操作
    _isSubmitting = true;
    debugPrint('已设置考试提交标志');

    setState(() {
      // UI更新
    });
    
    // 创建考试结果
    ExamResult result = ExamResult.create(
      examId: widget.exam.id,
      userId: UserData.currentUser?.id ?? 'unknown',
      answers: _answers,
      avatarPath: widget.avatarPath,
    );
    
    // 在保存前确保删除所有内部标记字段
    final Map<String, dynamic> finalAnswers = Map<String, dynamic>.from(_answers);
    if (finalAnswers.containsKey('_active_session')) {
      finalAnswers.remove('_active_session');
    }
    if (finalAnswers.containsKey('_last_activity')) {
      finalAnswers.remove('_last_activity');
    }
    
    // 创建新的ExamResult，不包含answerImages
    result = ExamResult.create(
      examId: result.examId,
      userId: result.userId,
      answers: finalAnswers,
      avatarPath: result.avatarPath,
    );
    
    // 添加答题照片到新的结果中
    for (var questionId in _answerImages.keys) {
      for (var imagePath in _answerImages[questionId]!) {
        result = result.addAnswerImage(questionId, imagePath);
      }
    }
    
    // 计算考试用时（分钟）
    final examDurationInMinutes = widget.exam.duration;
    final usedTimeInMinutes = (examDurationInMinutes - (_remainingSeconds / 60)).ceil();
    
    // 保存结果并标记考试完成
    try {
      debugPrint('=== 开始完成考试流程 ===');

      // 确定要删除的考试状态ID
      // 如果是恢复的考试，使用原始状态中的考试ID
      // 如果是新开始的考试，使用当前考试的ID
      final examIdForStateRemoval = widget.initialState?.examId ?? widget.exam.id;

      debugPrint('考试ID (用于显示): ${widget.exam.id}');
      debugPrint('考试ID (用于状态删除): $examIdForStateRemoval');
      debugPrint('用户ID: ${result.userId}');

      final success = await ExamStateService.completeExam(examIdForStateRemoval, result);

      if (success) {
        debugPrint('✅ 考试完成，结果已保存，考试状态已删除');

        // 导出考试结果到Excel（异步进行，不阻塞导航）
        ExamStateService.exportExamResultToExcel(
          result,
          widget.exam,
          usedTimeInMinutes
        ).then((filePath) {
          if (filePath != null) {
            debugPrint('考试结果已导出至: $filePath');

            // 打包考试结果为ZIP文件
            ExamStateService.packageExamResultsToZip(
              result,
              widget.exam,
              usedTimeInMinutes,
              filePath
            ).then((zipFilePath) {
              if (zipFilePath != null) {
                debugPrint('考试结果和照片已打包成ZIP: $zipFilePath');
              } else {
                debugPrint('考试结果打包失败');
              }
            });
          } else {
            debugPrint('考试结果导出失败');
          }
        });
      } else {
        debugPrint('❌ 考试结果保存失败或状态删除失败');
        // 即使保存失败，也继续导航，但记录错误
      }

      // 确保考试状态已经处理完成后再导航
      debugPrint('✅ 准备导航到结果页面');

      // 导航到结果页面
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => ResultScreen(exam: widget.exam, result: result),
            settings: RouteSettings(name: 'ResultScreen'),
          ),
        );
      }
    } catch (e) {
      debugPrint('❌ 完成考试时出错: $e');

      // 即使出错也要导航到结果页面
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => ResultScreen(exam: widget.exam, result: result),
            settings: RouteSettings(name: 'ResultScreen'),
          ),
        );
      }
    }
  }

  void _nextQuestion() {
    if (_currentIndex < widget.exam.questions.length - 1) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _previousQuestion() {
    if (_currentIndex > 0) {
      _pageController.previousPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  bool _isQuestionAnswered(String questionId) {
    // 检查是否有文字答案
    bool hasTextAnswer = _answers.containsKey(questionId) && _answers[questionId] != null;

    if (hasTextAnswer) {
      // 找到对应的题目
      final question = _findQuestionById(questionId);

      if (question != null && question.type == QuestionType.fillBlank) {
        // 填空题特殊处理
        final fillBlankQuestion = question as FillBlankQuestion;

        if (fillBlankQuestion.isMultiBlank) {
          // 多空填空题：检查所有空是否都已填写
          if (_answers[questionId] is List<String>) {
            final answers = _answers[questionId] as List<String>;
            // 确保所有空都有非空答案
            if (answers.length < fillBlankQuestion.blankCount) {
              hasTextAnswer = false;
            } else {
              hasTextAnswer = answers.every((answer) => answer.trim().isNotEmpty);
            }
          } else {
            hasTextAnswer = false;
          }
        } else {
          // 单空填空题：检查答案是否非空
          if (_answers[questionId] is String) {
            hasTextAnswer = (_answers[questionId] as String).trim().isNotEmpty;
          } else {
            hasTextAnswer = false;
          }
        }
      } else {
        // 其他题型的处理
        // 对于多选题，确保选择了至少一个选项
        if (_answers[questionId] is List) {
          hasTextAnswer = (_answers[questionId] as List).isNotEmpty;
        }

        // 对于文本答案，确保不是空字符串
        if (_answers[questionId] is String) {
          hasTextAnswer = (_answers[questionId] as String).trim().isNotEmpty;
        }
      }
    }

    // 检查是否有照片答案
    bool hasPhotoAnswer = _answerImages.containsKey(questionId) &&
                          _answerImages[questionId]!.isNotEmpty;

    // 如果有任一类型的答案，则认为问题已回答
    return hasTextAnswer || hasPhotoAnswer;
  }

  // 检查问题是否被标记
  bool _isQuestionMarked(String questionId) {
    return _markedQuestions.contains(questionId);
  }

  // 切换问题的标记状态
  void _toggleQuestionMark(String questionId) {
    setState(() {
      if (_markedQuestions.contains(questionId)) {
        _markedQuestions.remove(questionId);
      } else {
        _markedQuestions.add(questionId);
      }
    });
  }

  void _updateAnswer(String questionId, dynamic answer) {
    setState(() {
      _answers[questionId] = answer;
    });

    // 每次答题后保存考试状态
    _saveExamState();
  }

  // 更新多空填空题的答案
  void _updateMultiBlankAnswer(String questionId, int index, String value) {
    setState(() {
      // 确保答案是List<String>格式
      if (_answers[questionId] is! List<String>) {
        _answers[questionId] = <String>[];
      }

      final List<String> answers = _answers[questionId] as List<String>;

      // 确保列表长度足够
      while (answers.length <= index) {
        answers.add('');
      }

      // 更新指定位置的答案
      answers[index] = value;

      debugPrint('多空填空答案更新: 题目=$questionId, 第${index + 1}空="$value"');
      debugPrint('当前所有答案: $answers');
    });

    // 每次答题后保存考试状态
    _saveExamState();
  }

  @override
  Widget build(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    final double standardSpacing = 12.0; // 使用固定间距
    
    return WillPopScope(
      onWillPop: () async {
        // 拦截用户的返回操作，显示确认对话框
        final shouldPop = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('确认离开考试?'),
            content: const Text('离开将会保存当前答题状态，您可以稍后继续考试，但计时不会暂停。确定要离开吗?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () {
                  // 设置主动离开标记
                  _isLeavingExam = true;
                  Navigator.of(context).pop(true);
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                ),
                child: const Text('确认离开'),
              ),
            ],
          ),
        );
        return shouldPop ?? false;
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text(
            widget.exam.title,
            style: TextStyle(
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
              color: Colors.white,
              overflow: TextOverflow.ellipsis,
            ),
            maxLines: 1,
          ),
          backgroundColor: Colors.blue.shade800,
          foregroundColor: Colors.white,
          elevation: 0,
          toolbarHeight: 50.0, // 固定工具栏高度
          actions: [
            // 暂停按钮
            IconButton(
              icon: Icon(_isPaused ? Icons.play_arrow : Icons.pause),
              onPressed: _isPaused ? null : _pauseExam,
              tooltip: '暂停考试',
            ),
            Center(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 4.0),
                margin: EdgeInsets.only(right: 12.0),
                decoration: BoxDecoration(
                  color: _isPaused 
                    ? Colors.orange.shade700  // 暂停时使用橙色
                    : Colors.blue.shade700,
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Row(
                  children: [
                    Icon(_isPaused ? Icons.pause : Icons.timer, size: 14),
                    SizedBox(width: 4),
                    Text(
                      _formatTime(_remainingSeconds),
                      style: TextStyle(
                        fontSize: 14.0,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                    if (_isPaused)
                      Text(
                        ' (已暂停)',
                        style: TextStyle(
                          fontSize: 12.0,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        endDrawer: _buildQuestionNavigationDrawer(),
        body: Column(
          children: [
            // 进度条
            LinearProgressIndicator(
              value: (_currentIndex + 1) / widget.exam.questions.length,
              backgroundColor: Colors.grey.shade200,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.blue.shade600),
              minHeight: 3,
            ),
            
            // 问题计数器和已答题数
            Padding(
              padding: EdgeInsets.symmetric(
                horizontal: standardSpacing,
                vertical: 6.0,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade100,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          '题目 ${_currentIndex + 1}/${widget.exam.questions.length}',
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue.shade800,
                          ),
                        ),
                      ),
                      SizedBox(width: 8),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                        decoration: BoxDecoration(
                          color: _getAnsweredCount() == widget.exam.questions.length
                              ? Colors.green.shade100
                              : Colors.orange.shade100,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          '已答: ${_getAnsweredCount()}/${widget.exam.questions.length}',
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            color: _getAnsweredCount() == widget.exam.questions.length
                                ? Colors.green.shade800
                                : Colors.orange.shade800,
                          ),
                        ),
                      ),
                    ],
                  ),
                  // 导航按钮
                  ElevatedButton.icon(
                    onPressed: () => _scaffoldKey.currentState?.openEndDrawer(),
                    icon: Icon(Icons.menu, size: 14),
                    label: Text(
                      '题目导航',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey.shade200,
                      foregroundColor: Colors.black87,
                      padding: EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      minimumSize: Size(10, 10),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 题目内容区域
            Expanded(
              child: PageView.builder(
                controller: _pageController,
                onPageChanged: (index) {
                  setState(() {
                    _currentIndex = index;
                  });
                },
                itemCount: widget.exam.questions.length,
                itemBuilder: (context, index) {
                  final question = widget.exam.questions[index];
                  return SingleChildScrollView(
                    padding: EdgeInsets.symmetric(
                      horizontal: standardSpacing,
                      vertical: 8.0,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildQuestionHeader(question, isTablet),
                        SizedBox(height: 12.0),
                        _buildQuestionContent(question, isTablet),
                        SizedBox(height: 16.0),
                      ],
                    ),
                  );
                },
              ),
            ),
            
            // 底部导航栏
            _buildBottomBar(isTablet),
          ],
        ),
      ),
    );
  }

  // 构建题目导航抽屉
  Widget _buildQuestionNavigationDrawer() {
    return Drawer(
      width: 300, // 调整宽度
      child: Column(
        children: [
          Container(
            color: Colors.white,
            padding: EdgeInsets.symmetric(
              vertical: 12.0,
              horizontal: 16.0,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 24), // 为状态栏留出空间
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '答题卡',
                      style: TextStyle(
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    IconButton(
                      icon: Icon(Icons.close, color: Colors.black87, size: 20),
                      onPressed: () => Navigator.of(context).pop(),
                      constraints: BoxConstraints(
                        minWidth: 40,
                        minHeight: 40,
                      ),
                      padding: EdgeInsets.zero,
                    ),
                  ],
                ),
                SizedBox(height: 12),
                // 题目状态图例
                Column(
                  children: [
                    Row(
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.circle,
                              size: 16,
                              color: Colors.blue,
                            ),
                            SizedBox(width: 4),
                            Text('已做', style: TextStyle(fontSize: 14)),
                          ],
                        ),
                        SizedBox(width: 20),
                        Row(
                          children: [
                            Icon(
                              Icons.circle_outlined,
                              size: 16,
                              color: Colors.grey,
                            ),
                            SizedBox(width: 4),
                            Text('未做', style: TextStyle(fontSize: 14)),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(height: 8),
                    Row(
                      children: [
                        Row(
                          children: [
                            Container(
                              width: 16,
                              height: 16,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: Colors.orange,
                              ),
                              child: Icon(
                                Icons.bookmark,
                                size: 10,
                                color: Colors.white,
                              ),
                            ),
                            SizedBox(width: 4),
                            Text('已标记', style: TextStyle(fontSize: 14)),
                          ],
                        ),
                        SizedBox(width: 20),
                        Row(
                          children: [
                            Container(
                              width: 16,
                              height: 16,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: Colors.green,
                                border: Border.all(
                                  color: Colors.green,
                                  width: 2,
                                ),
                              ),
                            ),
                            SizedBox(width: 4),
                            Text('当前题', style: TextStyle(fontSize: 14)),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ],
                  ),
          ),
          Divider(height: 1, thickness: 1, color: Colors.grey.shade200),
          
          // 使用Expanded和ListView来包含所有题型分组
          Expanded(
            child: ListView(
              padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
              children: [
                // 按题型分组显示题目
                _buildQuestionTypeGroup(QuestionType.singleChoice, '单选题'),
                SizedBox(height: 16),
                _buildQuestionTypeGroup(QuestionType.multipleChoice, '多选题'),
                SizedBox(height: 16),
                _buildQuestionTypeGroup(QuestionType.trueOrFalse, '判断题'),
                SizedBox(height: 16),
                _buildQuestionTypeGroup(QuestionType.fillBlank, '填空题'),
                SizedBox(height: 16),
                _buildQuestionTypeGroup(QuestionType.shortAnswer, '简答题'),
              ],
            ),
          ),
          
          // 答题进度和提交按钮
          Container(
            padding: EdgeInsets.all(12.0),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                top: BorderSide(color: Colors.grey.shade300),
              ),
            ),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '已答: ${_getAnsweredCount()}/${widget.exam.questions.length}',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: _getAnsweredCount() == widget.exam.questions.length
                            ? Colors.green
                            : Colors.orange,
                      ),
                    ),
                    Text(
                      '已标记: ${_markedQuestions.length}',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: Colors.orange,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8),
                LinearProgressIndicator(
                  value: _getAnsweredCount() / widget.exam.questions.length,
                  backgroundColor: Colors.grey.shade300,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    _getAnsweredCount() == widget.exam.questions.length
                        ? Colors.green
                        : Colors.orange,
                  ),
                  minHeight: 6,
                ),
                SizedBox(height: 12),
                ElevatedButton(
                  onPressed: () {
                    Navigator.of(context).pop(); // 先关闭抽屉
                    _submitExam(); // 然后调用提交方法
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red.shade700,
                    minimumSize: Size(double.infinity, 40),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: Text(
                    '提交考试',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  // 新增：构建题型分组
  Widget _buildQuestionTypeGroup(QuestionType type, String title) {
    // 筛选该类型的所有题目
    final questionsOfType = widget.exam.questions.where((q) => q.type == type).toList();
    
    // 如果没有此类型的题目，则不显示此组
    if (questionsOfType.isEmpty) {
      return SizedBox.shrink();
    }
    
    // 计算该类型题目的分数总和
    double totalScore = questionsOfType.fold(0, (sum, q) => sum + q.score);
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 题型标题和描述
        Text(
          '$title (共${questionsOfType.length}题，每题${questionsOfType.first.score}分)',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: Colors.black87,
          ),
        ),
        SizedBox(height: 8),
        
        // 题号网格
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: List.generate(questionsOfType.length, (index) {
            final question = questionsOfType[index];
            final questionId = question.id;
            
            // 获取问题在所有题目中的索引，用于导航
            final globalIndex = widget.exam.questions.indexWhere((q) => q.id == questionId);
            
            // 确定按钮样式
            final bool isAnswered = _isQuestionAnswered(questionId);
            final bool isCurrentQuestion = globalIndex == _currentIndex;
            final bool isMarked = _isQuestionMarked(questionId);
            
            // 确定按钮颜色和样式
            Color buttonColor;
            Color borderColor;
            Color textColor;
            Widget? overlayIcon;
            
            if (isCurrentQuestion) {
              // 当前题目：绿色边框，突出显示
              buttonColor = isAnswered ? Colors.blue : Colors.white;
              borderColor = Colors.green;
              textColor = isAnswered ? Colors.white : Colors.black87;
            } else if (isMarked && isAnswered) {
              // 已标记且已做：蓝色背景 + 橙色标记图标
              buttonColor = Colors.blue;
              borderColor = Colors.blue;
              textColor = Colors.white;
              overlayIcon = Positioned(
                top: 0,
                right: 0,
                child: Container(
                  width: 12,
                  height: 12,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.orange,
                  ),
                  child: Icon(
                    Icons.bookmark,
                    size: 8,
                    color: Colors.white,
                  ),
                ),
              );
            } else if (isMarked) {
              // 仅标记未做：橙色背景
              buttonColor = Colors.orange;
              borderColor = Colors.orange;
              textColor = Colors.white;
              overlayIcon = Positioned(
                top: 0,
                right: 0,
                child: Container(
                  width: 12,
                  height: 12,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.orange.shade700,
                  ),
                  child: Icon(
                    Icons.bookmark,
                    size: 8,
                    color: Colors.white,
                  ),
                ),
              );
            } else if (isAnswered) {
              // 仅已做：蓝色背景
              buttonColor = Colors.blue;
              borderColor = Colors.blue;
              textColor = Colors.white;
            } else {
              // 未做：白色背景
              buttonColor = Colors.white;
              borderColor = Colors.grey.shade400;
              textColor = Colors.black87;
            }
            
            return InkWell(
              onTap: () {
                _pageController.animateToPage(
                  globalIndex,
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                );
                Navigator.of(context).pop(); // 关闭抽屉
              },
              child: Stack(
                children: [
                  Container(
                    width: 36,
                    height: 36,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: buttonColor,
                      border: Border.all(
                        color: borderColor,
                        width: isCurrentQuestion ? 3 : 1,
                      ),
                    ),
                    child: Text(
                      '${index + 1}',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: textColor,
                      ),
                    ),
                  ),
                  if (overlayIcon != null) overlayIcon,
                ],
              ),
            );
          }),
        ),
      ],
    );
  }

  Widget _buildQuestionHeader(Question question, bool isTablet) {
    String typeText = _getQuestionTypeText(question.type);
    final bool isMarked = _isQuestionMarked(question.id);
    
    return Container(
      padding: EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.blue.shade100),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade100,
                      borderRadius: BorderRadius.circular(12.0),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          _getIconForQuestionType(question.type),
                          color: Colors.blue.shade700,
                          size: 14.0,
                        ),
                        SizedBox(width: 4.0),
                        Text(
                          typeText,
                          style: TextStyle(
                            fontSize: 12.0,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue.shade800,
                          ),
                        ),
                      ],
                    ),
              ),
              // 标记按钮
              InkWell(
                onTap: () => _toggleQuestionMark(question.id),
                borderRadius: BorderRadius.circular(20),
                child: Container(
                  padding: EdgeInsets.all(6),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: isMarked ? Colors.orange.shade100 : Colors.transparent,
                  ),
                  child: Icon(
                    isMarked ? Icons.bookmark : Icons.bookmark_border,
                    color: isMarked ? Colors.orange : Colors.grey.shade600,
                    size: 20,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 12.0),
          Text(
            question.text,
            style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  // 修改底部导航栏，使其更紧凑
  Widget _buildBottomBar(bool isTablet) {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 12.0,
        vertical: 6.0,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 3,
            offset: Offset(0, -1),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 上一题按钮
          OutlinedButton.icon(
            onPressed: _currentIndex > 0 ? _previousQuestion : null,
            icon: Icon(Icons.arrow_back_ios, size: 12),
            label: Text('上一题', style: TextStyle(fontSize: 12)),
            style: OutlinedButton.styleFrom(
              side: BorderSide(
                color: _currentIndex > 0 ? Colors.blue : Colors.grey.shade300,
                width: 1.0,
              ),
              foregroundColor: _currentIndex > 0 ? Colors.blue : Colors.grey,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
              minimumSize: Size(80, 32),
              padding: EdgeInsets.symmetric(horizontal: 6, vertical: 0),
            ),
          ),
          
          // 提交按钮
          ElevatedButton(
            onPressed: _submitExam,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red.shade700,
              disabledBackgroundColor: Colors.red.shade200,
              minimumSize: Size(80, 32),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
            ),
            child: Text(
              '提交考试',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          
          // 下一题按钮
          OutlinedButton.icon(
            onPressed: _currentIndex < widget.exam.questions.length - 1 ? _nextQuestion : null,
            icon: Icon(Icons.arrow_forward_ios, size: 12),
            label: Text('下一题', style: TextStyle(fontSize: 12)),
            style: OutlinedButton.styleFrom(
              side: BorderSide(
                color: _currentIndex < widget.exam.questions.length - 1 ? Colors.blue : Colors.grey.shade300,
                width: 1.0,
              ),
              foregroundColor: _currentIndex < widget.exam.questions.length - 1 ? Colors.blue : Colors.grey,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
              minimumSize: Size(80, 32),
              padding: EdgeInsets.symmetric(horizontal: 6, vertical: 0),
            ),
          ),
        ],
      ),
    );
  }

  String _getQuestionTypeText(QuestionType type) {
    switch (type) {
      case QuestionType.singleChoice:
        return '单选题';
      case QuestionType.multipleChoice:
        return '多选题';
      case QuestionType.fillBlank:
        return '填空题';
      case QuestionType.trueOrFalse:
        return '判断题';
      case QuestionType.shortAnswer:
        return '简答题';
    }
  }

  IconData _getIconForQuestionType(QuestionType type) {
    switch (type) {
      case QuestionType.singleChoice:
        return Icons.radio_button_checked;
      case QuestionType.multipleChoice:
        return Icons.check_box;
      case QuestionType.fillBlank:
        return Icons.short_text;
      case QuestionType.trueOrFalse:
        return Icons.rule;
      case QuestionType.shortAnswer:
        return Icons.notes;
    }
  }

  Widget _buildQuestionContent(Question question, bool isTablet) {
    switch (question.type) {
      case QuestionType.singleChoice:
        return _buildSingleChoiceQuestion(question as SingleChoiceQuestion, isTablet);
      case QuestionType.multipleChoice:
        return _buildMultipleChoiceQuestion(question as MultipleChoiceQuestion, isTablet);
      case QuestionType.fillBlank:
        return _buildFillBlankQuestion(question as FillBlankQuestion, isTablet);
      case QuestionType.trueOrFalse:
        return _buildTrueOrFalseQuestion(question as TrueOrFalseQuestion, isTablet);
      case QuestionType.shortAnswer:
        return _buildShortAnswerQuestion(question as ShortAnswerQuestion, isTablet);
    }
  }

  Widget _buildSingleChoiceQuestion(SingleChoiceQuestion question, bool isTablet) {
    return Card(
      elevation: 1,
      margin: EdgeInsets.only(top: 12.0),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8.0),
        side: BorderSide(color: Colors.grey.shade200),
      ),
      child: Padding(
        padding: EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 选项
            ...question.choices.map((choice) {
              final isSelected = _answers[question.id] == choice.id;
              return Container(
                margin: EdgeInsets.symmetric(vertical: 3.0),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.blue.shade50 : Colors.transparent,
                  borderRadius: BorderRadius.circular(6.0),
                  border: Border.all(
                    color: isSelected ? Colors.blue.shade400 : Colors.grey.shade300,
                  ),
                ),
                child: RadioListTile<String>(
                  title: Text(
                    "${choice.id}. ${choice.text}",
                    style: TextStyle(
                      fontSize: 14.0,
                    ),
                  ),
                  value: choice.id,
                  groupValue: _answers[question.id] as String?,
                  onChanged: (value) {
                    _updateAnswer(question.id, value);
                  },
                  activeColor: Colors.blue.shade800,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 10.0, 
                    vertical: 6.0,
                  ),
                  dense: true,
                  secondary: isSelected 
                      ? Icon(Icons.check_circle, color: Colors.green, size: 20.0)
                      : null,
                ),
              );
            }).toList(),
          ],
        ),
      ),
    );
  }

  Widget _buildMultipleChoiceQuestion(MultipleChoiceQuestion question, bool isTablet) {
    // Ensure _answers[question.id] is a List<String>
    if (_answers[question.id] == null) {
      _answers[question.id] = <String>[];
    }

    final selectedOptions = _answers[question.id] as List<dynamic>? ?? [];

    return Card(
      elevation: 1,
      margin: EdgeInsets.only(top: 12.0),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8.0),
        side: BorderSide(color: Colors.grey.shade200),
      ),
      child: Padding(
        padding: EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 选项
            ...question.choices.map((choice) {
              final isSelected = selectedOptions.contains(choice.id);
              return Container(
                margin: EdgeInsets.symmetric(vertical: 3.0),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.blue.shade50 : Colors.transparent,
                  borderRadius: BorderRadius.circular(6.0),
                  border: Border.all(
                    color: isSelected ? Colors.blue.shade400 : Colors.grey.shade300,
                  ),
                ),
                child: CheckboxListTile(
                  title: Text(
                    "${choice.id}. ${choice.text}",
                    style: TextStyle(
                      fontSize: 14.0,
                    ),
                  ),
                  value: isSelected,
                  onChanged: (checked) {
                    setState(() {
                      final List<String> updatedList = List<String>.from(selectedOptions.map((e) => e.toString()));
                      if (checked == true) {
                        if (!updatedList.contains(choice.id)) {
                          updatedList.add(choice.id);
                        }
                      } else {
                        updatedList.remove(choice.id);
                      }
                      _updateAnswer(question.id, updatedList);
                    });
                  },
                  activeColor: Colors.blue.shade800,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 10.0, 
                    vertical: 6.0,
                  ),
                  dense: true,
                  checkColor: Colors.white,
                  secondary: isSelected
                      ? Icon(Icons.check_circle, color: Colors.green, size: 20.0)
                      : null,
                ),
              );
            }).toList(),
          ],
        ),
      ),
    );
  }

  Widget _buildFillBlankQuestion(FillBlankQuestion question, bool isTablet) {
    // 检查是否为多空填空题
    final isMultiBlank = question.isMultiBlank;
    final blankCount = question.blankCount;

    // 确保答案格式正确
    if (_answers[question.id] == null) {
      if (isMultiBlank) {
        // 多空填空题使用List<String>存储答案
        _answers[question.id] = List<String>.filled(blankCount, '');
      } else {
        // 单空填空题使用String存储答案
        _answers[question.id] = '';
      }
    }

    return Container(
      margin: EdgeInsets.only(top: 12.0),
      padding: EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.grey.shade300),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.shade100,
            blurRadius: 3,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            isMultiBlank ? '请填写答案（共${blankCount}个空）：' : '请填写答案：',
            style: TextStyle(
              fontSize: 14.0,
              fontWeight: FontWeight.bold,
              color: Colors.grey.shade700,
            ),
          ),
          SizedBox(height: 10.0),
          if (isMultiBlank)
            // 多空填空题 - 显示多个输入框
            ...List.generate(blankCount, (index) {
              // 为每个空创建单独的控制器
              final controllerId = '${question.id}_$index';
              if (!_textControllers.containsKey(controllerId)) {
                final currentAnswers = _answers[question.id] as List<String>;
                _textControllers[controllerId] = TextEditingController(
                  text: index < currentAnswers.length ? currentAnswers[index] : ''
                );
              }

              return Padding(
                padding: EdgeInsets.only(bottom: 8.0),
                child: Row(
                  children: [
                    Container(
                      width: 40,
                      child: Text(
                        '第${index + 1}空:',
                        style: TextStyle(
                          fontSize: 13.0,
                          fontWeight: FontWeight.w500,
                          color: Colors.grey.shade600,
                        ),
                      ),
                    ),
                    SizedBox(width: 8.0),
                    Expanded(
                      child: TextField(
                        onChanged: (value) {
                          _updateMultiBlankAnswer(question.id, index, value);
                        },
                        decoration: InputDecoration(
                          hintText: '请输入第${index + 1}个答案',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(6.0),
                            borderSide: BorderSide(color: Colors.blue.shade200),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(6.0),
                            borderSide: BorderSide(color: Colors.blue.shade700, width: 2),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 12.0,
                            vertical: 8.0,
                          ),
                          filled: true,
                          fillColor: Colors.grey.shade50,
                          hintStyle: TextStyle(fontSize: 13.0),
                          isDense: true,
                        ),
                        controller: _textControllers[controllerId],
                        style: TextStyle(fontSize: 14.0),
                      ),
                    ),
                  ],
                ),
              );
            })
          else
            // 单空填空题 - 显示单个输入框
            TextField(
              onChanged: (value) {
                _updateAnswer(question.id, value);
              },
              decoration: InputDecoration(
                hintText: '请输入答案',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(6.0),
                  borderSide: BorderSide(color: Colors.blue.shade200),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(6.0),
                  borderSide: BorderSide(color: Colors.blue.shade700, width: 2),
                ),
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 12.0,
                  vertical: 10.0,
                ),
                filled: true,
                fillColor: Colors.grey.shade50,
                hintStyle: TextStyle(fontSize: 14.0),
              ),
              controller: _textControllers[question.id],
              style: TextStyle(fontSize: 14.0),
            ),
        ],
      ),
    );
  }

  Widget _buildTrueOrFalseQuestion(TrueOrFalseQuestion question, bool isTablet) {
    return Card(
      elevation: 1,
      margin: EdgeInsets.only(top: 12.0),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8.0),
        side: BorderSide(color: Colors.grey.shade200),
      ),
      child: Padding(
        padding: EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 3.0),
              decoration: BoxDecoration(
                color: _answers[question.id] == true ? Colors.blue.shade50 : Colors.transparent,
                borderRadius: BorderRadius.circular(6.0),
                border: Border.all(
                  color: _answers[question.id] == true ? Colors.blue.shade400 : Colors.grey.shade300,
                ),
              ),
              child: RadioListTile<bool>(
                title: Text(
                  '正确',
                  style: TextStyle(
                    fontSize: 14.0,
                  ),
                ),
                value: true,
                groupValue: _answers[question.id] as bool?,
                onChanged: (value) {
                  _updateAnswer(question.id, value);
                },
                activeColor: Colors.blue.shade800,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 10.0, 
                  vertical: 6.0,
                ),
                dense: true,
                secondary: _answers[question.id] == true 
                    ? Icon(Icons.check_circle, color: Colors.green, size: 20.0)
                    : null,
              ),
            ),
            SizedBox(height: 6.0),
            Container(
              margin: EdgeInsets.symmetric(vertical: 3.0),
              decoration: BoxDecoration(
                color: _answers[question.id] == false ? Colors.blue.shade50 : Colors.transparent,
                borderRadius: BorderRadius.circular(6.0),
                border: Border.all(
                  color: _answers[question.id] == false ? Colors.blue.shade400 : Colors.grey.shade300,
                ),
              ),
              child: RadioListTile<bool>(
                title: Text(
                  '错误',
                  style: TextStyle(
                    fontSize: 14.0,
                  ),
                ),
                value: false,
                groupValue: _answers[question.id] as bool?,
                onChanged: (value) {
                  _updateAnswer(question.id, value);
                },
                activeColor: Colors.blue.shade800,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 10.0, 
                  vertical: 6.0,
                ),
                dense: true,
                secondary: _answers[question.id] == false 
                    ? Icon(Icons.check_circle, color: Colors.green, size: 20.0)
                    : null,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildShortAnswerQuestion(ShortAnswerQuestion question, bool isTablet) {
    // 获取当前问题的答题照片
    final List<String> answerImages = _getAnswerImages(question.id);
    
    return Container(
      margin: EdgeInsets.only(top: 12.0),
      padding: EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.grey.shade300),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.shade100,
            blurRadius: 3,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '请输入答案或上传照片：',
            style: TextStyle(
              fontSize: 14.0,
              fontWeight: FontWeight.bold,
              color: Colors.grey.shade700,
            ),
          ),
          SizedBox(height: 10.0),
          TextField(
            onChanged: (value) {
              _updateAnswer(question.id, value);
            },
            maxLines: 4,
            minLines: 3,
            decoration: InputDecoration(
              hintText: '可以在此输入文字答案，或直接通过下方按钮上传照片',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(6.0),
                borderSide: BorderSide(color: Colors.blue.shade200),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(6.0),
                borderSide: BorderSide(color: Colors.blue.shade700, width: 2),
              ),
              contentPadding: EdgeInsets.symmetric(
                horizontal: 12.0,
                vertical: 10.0,
              ),
              filled: true,
              fillColor: Colors.grey.shade50,
              hintStyle: TextStyle(fontSize: 14.0),
            ),
            controller: _textControllers[question.id],
            style: TextStyle(fontSize: 14.0),
          ),
          SizedBox(height: 16.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '添加答题照片：',
                style: TextStyle(
                  fontSize: 14.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey.shade700,
                ),
              ),
              Row(
                children: [
                  // 拍照按钮
                  ElevatedButton.icon(
                    onPressed: () => _takePhoto(question.id),
                    icon: Icon(Icons.camera_alt, size: 16.0),
                    label: Text('拍照'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue.shade600,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
                      textStyle: TextStyle(fontSize: 12.0),
                    ),
                  ),
                ],
              ),
            ],
          ),
          // 显示已添加的照片
          if (answerImages.isNotEmpty) ...[
            SizedBox(height: 12.0),
            Text(
              '已添加的照片：',
              style: TextStyle(
                fontSize: 14.0,
                fontWeight: FontWeight.bold,
                color: Colors.grey.shade700,
              ),
            ),
            SizedBox(height: 8.0),
            Container(
              height: 100.0,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: answerImages.length,
                itemBuilder: (context, index) {
                  return Container(
                    margin: EdgeInsets.only(right: 8.0),
                    width: 100.0,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey.shade300),
                      borderRadius: BorderRadius.circular(4.0),
                    ),
                    child: Stack(
                      children: [
                        // 显示图片
                        Center(
                          child: Image.file(
                            File(answerImages[index]),
                            fit: BoxFit.cover,
                            width: 100.0,
                            height: 100.0,
                          ),
                        ),
                        // 删除按钮
                        Positioned(
                          top: 0,
                          right: 0,
                          child: InkWell(
                            onTap: () => _removeAnswerImage(question.id, answerImages[index]),
                            child: Container(
                              padding: EdgeInsets.all(4.0),
                              decoration: BoxDecoration(
                                color: Colors.red.withOpacity(0.7),
                                shape: BoxShape.circle,
                              ),
                              child: Icon(
                                Icons.close,
                                size: 14.0,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 获取问题的答题照片
  List<String> _getAnswerImages(String questionId) {
    return _answerImages[questionId] ?? [];
  }
  
  // 拍照并添加到答题照片
  Future<void> _takePhoto(String questionId) async {
    // 获取题目类型，确保只有简答题能添加照片
    final Question? question = _findQuestionById(questionId);
    if (question == null || question.type != QuestionType.shortAnswer) {
      // 显示错误消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('只有简答题支持照片上传'),
          backgroundColor: Colors.red.shade600,
        ),
      );
      return;
    }

    // 设置全局拍照状态标记
    PhotoStateService().startPhotoOperation();
    _isTakingPhoto = true;
    debugPrint('开始拍照，设置全局拍照状态标记');

    final File? photo = await ImageService.takePhoto();
    if (photo != null) {
      _addAnswerImage(questionId, photo.path);
    } else {
      // 如果拍照取消，重置标记
      PhotoStateService().endPhotoOperation();
      _isTakingPhoto = false;
      debugPrint('拍照取消，重置全局拍照状态标记');
    }
  }
  
  // 从相册选择图片并添加到答题照片
  Future<void> _pickImage(String questionId) async {
    // 获取题目类型，确保只有简答题能添加照片
    final Question? question = _findQuestionById(questionId);
    if (question == null || question.type != QuestionType.shortAnswer) {
      // 显示错误消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('只有简答题支持照片上传'),
          backgroundColor: Colors.red.shade600,
        ),
      );
      return;
    }

    // 设置全局拍照状态标记（相册选择也可能触发应用切换）
    PhotoStateService().startPhotoOperation();
    _isTakingPhoto = true;
    debugPrint('开始选择相册图片，设置全局拍照状态标记');

    final File? image = await ImageService.pickImageFromGallery();
    if (image != null) {
      _addAnswerImage(questionId, image.path);
    } else {
      // 如果选择取消，重置标记
      PhotoStateService().endPhotoOperation();
      _isTakingPhoto = false;
      debugPrint('相册选择取消，重置全局拍照状态标记');
    }
  }
  
  // 添加答题照片
  void _addAnswerImage(String questionId, String imagePath) {
    setState(() {
      if (_answerImages.containsKey(questionId)) {
        _answerImages[questionId]!.add(imagePath);
      } else {
        _answerImages[questionId] = [imagePath];
      }
    });

    // 成功添加照片后，结束全局拍照状态
    PhotoStateService().endPhotoOperation();
    _isTakingPhoto = false;
    debugPrint('照片添加成功，结束全局拍照状态');

    // 延迟保存考试状态，避免立即触发状态检查
    Future.delayed(Duration(milliseconds: 100), () {
      if (mounted) {
        _saveExamState();
      }
    });
  }
  
  // 删除答题照片
  void _removeAnswerImage(String questionId, String imagePath) {
    setState(() {
      if (_answerImages.containsKey(questionId)) {
        _answerImages[questionId]!.remove(imagePath);
        
        // 如果列表为空，删除该键
        if (_answerImages[questionId]!.isEmpty) {
          _answerImages.remove(questionId);
        }
      }
    });
    
    // 删除文件
    ImageService.deleteImage(imagePath);
    
    // 自动保存考试状态
    _saveExamState();
  }
  
  // 保存考试状态
  Future<void> _saveExamState() async {
    try {
      // 如果考试已经提交，不再保存状态
      if (_isSubmitting) {
        debugPrint('考试已提交，跳过保存考试状态');
        return;
      }

      final currentUser = UserData.currentUser;
      if (currentUser == null) {
        debugPrint('保存考试状态失败: 当前用户为空');
        return;
      }

      // 统计实际答题数量（排除系统标记）
      final actualAnswerCount = _answers.entries
          .where((entry) => !entry.key.startsWith('_'))
          .length;

      // 使用正确的考试ID
      final examIdForSave = widget.initialState?.examId ?? widget.exam.id;

      debugPrint('=== 保存考试状态 ===');
      debugPrint('考试ID: $examIdForSave');
      debugPrint('剩余时间: $_remainingSeconds 秒');
      debugPrint('实际答题数量: $actualAnswerCount');

      // 构建包含答题照片的完整答案，但不包含系统标记
      final Map<String, dynamic> completeAnswers = <String, dynamic>{};

      // 只复制实际的答题数据，排除系统标记
      _answers.forEach((key, value) {
        if (!key.startsWith('_')) {
          completeAnswers[key] = value;
        }
      });

      // 添加答题照片信息
      if (_answerImages.isNotEmpty) {
        completeAnswers['_answerImages'] = _answerImages;
        debugPrint('包含答题照片: ${_answerImages.length} 个题目');
      }

      // 活动时间戳现在由ExamState管理，不需要在answers中设置

      debugPrint('准备保存的实际答案数量: ${completeAnswers.entries.where((e) => !e.key.startsWith('_')).length}');

      // 保存状态并输出日志
      final result = await ExamStateService.autoSaveExamState(
        examIdForSave,
        completeAnswers,
        _remainingSeconds,
      );

      if (result) {
        debugPrint('✅ 考试状态保存成功');
      } else {
        debugPrint('❌ 考试状态保存失败');
      }
    } catch (e) {
      debugPrint('❌ 保存考试状态时出错: $e');
    }
  }

  // 计算已回答题目的数量（包含文字答案和照片答案）
  int _getAnsweredCount() {
    // 创建一个集合存储已回答的题目ID
    Set<String> answeredQuestionIds = {};

    // 遍历所有题目，使用 _isQuestionAnswered 方法来判断
    for (var question in widget.exam.questions) {
      if (_isQuestionAnswered(question.id)) {
        answeredQuestionIds.add(question.id);
      }
    }

    return answeredQuestionIds.length;
  }

  // 根据ID查找题目
  Question? _findQuestionById(String questionId) {
    for (var question in widget.exam.questions) {
      if (question.id == questionId) {
        return question;
      }
    }
    return null;
  }

  // 新增：暂停考试方法
  void _pauseExam() {
    // 确保组件仍然挂载
    if (!mounted) return;
    
    // 如果已经暂停，不重复操作
    if (_isPaused) return;
    
    // 显示密码输入对话框
    showDialog(
      context: context,
      barrierDismissible: false, // 防止点击外部关闭对话框
      builder: (context) => AlertDialog(
        title: Text('管理员验证'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '请输入管理员密码以暂停考试',
                style: TextStyle(fontSize: 14),
              ),
              SizedBox(height: 12),
              TextField(
                controller: _passwordController,
                obscureText: true,
                decoration: InputDecoration(
                  labelText: '管理员密码',
                  border: OutlineInputBorder(),
                  contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              _passwordController.clear();
              Navigator.of(context).pop();
            },
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 验证管理员登录密码
              if (UserData.verifyAdminPassword(_passwordController.text)) {
                _passwordController.clear();
                Navigator.of(context).pop();

                // 暂停考试
                setState(() {
                  _isPaused = true;
                });

                // 保存当前答案
                _saveExamState();

                // 显示已暂停界面
                _showPausedDialog();
              } else {
                // 密码错误，显示错误信息
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text('密码错误，请重试'),
                    backgroundColor: Colors.red,
                  ),
                );
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
            ),
            child: Text('验证'),
          ),
        ],
      ),
    );
  }
  
  // 新增：显示暂停对话框
  void _showPausedDialog() {
    // 如果当前不是暂停状态，不显示对话框
    if (!_isPaused) return;
    
    // 确保组件仍然挂载
    if (!mounted) return;
    
    showDialog(
      context: context,
      barrierDismissible: false, // 防止点击外部关闭对话框
      builder: (context) => WillPopScope(
        onWillPop: () async => false, // 禁止返回键关闭对话框
        child: AlertDialog(
          title: Text('考试已暂停'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.pause_circle_filled,
                size: 64,
                color: Colors.orange,
              ),
              SizedBox(height: 16),
              Text(
                '考试已暂停，剩余时间: ${_formatTime(_remainingSeconds)}',
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 8),
              Text(
                '已自动保存所有答案',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.green,
                ),
              ),
            ],
          ),
          actions: [
            ElevatedButton(
              onPressed: () {
                // 验证密码后恢复考试
                _verifyAndResumeExam();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
              ),
              child: Text('恢复考试'),
            ),
          ],
        ),
      ),
    );
  }
  
  // 新增：验证密码并恢复考试
  void _verifyAndResumeExam() {
    // 弹出密码验证对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('管理员验证'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('请输入管理员密码以恢复考试'),
            SizedBox(height: 16),
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: InputDecoration(
                labelText: '管理员密码',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 验证管理员登录密码
              if (UserData.verifyAdminPassword(_passwordController.text)) {
                _passwordController.clear();
                if (mounted) {
                  Navigator.of(context).pop();
                }

                // 使用PostFrameCallback确保在正确的构建周期执行
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  if (mounted) {
                    // 直接恢复考试
                    resumeExam();
                  }
                });
              } else {
                // 密码错误，显示错误信息
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('密码错误，请重试'),
                      backgroundColor: Colors.red,
                    ),
                  );
                }
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
            ),
            child: Text('验证'),
          ),
        ],
      ),
    );
  }

  // 新增：恢复考试方法
  void resumeExam() {
    // 确保我们在状态组件挂载时执行
    if (!mounted) return;
    
    // 解除暂停状态
    setState(() {
      _isPaused = false;
    });
    
    // 保存当前状态
    _saveExamState();
    
    // 关闭暂停对话框
    if (Navigator.of(context).canPop()) {
      Navigator.of(context).pop();
    }
    
    // 显示提示
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('考试已恢复'),
        backgroundColor: Colors.green,
        duration: Duration(seconds: 2),
      ),
    );
  }
} 